package com.sdy.supermarket.web.controller.dept;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sdy.approval.api.ApprovalAllApi;
import com.sdy.auth.api.model.UserInfo;
import com.sdy.auth.client.service.SsoService;
import com.sdy.common.model.BizException;
import com.sdy.common.model.Response;
import com.sdy.common.utils.Assert;
import com.sdy.common.utils.StringUtil;
import com.sdy.mvc.controller.BaseController;
import com.sdy.supermarket.biz.model.GsApp;
import com.sdy.supermarket.biz.model.GsApproveFlow;
import com.sdy.supermarket.biz.model.GsOrderItem;
import com.sdy.supermarket.biz.service.GsAppIpApplyService;
import com.sdy.supermarket.biz.service.GsAppService;
import com.sdy.supermarket.biz.service.GsOrderItemService;
import com.sdy.supermarket.biz.service.GsOrderService;
import com.sdy.supermarket.biz.utils.PageUtils;
import com.sdy.supermarket.biz.vo.*;
import com.sdy.usercenter.api.UserQueryApi;
import com.sdy.usercenter.api.dto.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;

/**
 * 部门管理员后台
 *
 * @author zhouziqiang
 */
@RestController
@Slf4j
@RequestMapping("/dept/workbench")
public class DeptWorkbenchController extends BaseController {
    @Autowired
    private GsAppService gsAppService;
    @Autowired
    private SsoService ssoService;
    @Autowired
    private GsOrderService gsOrderService;
    @Autowired
    private ApprovalAllApi approvalAllApi;
    @Autowired
    private GsOrderItemService gsOrderItemService;
    @Autowired
    private GsAppIpApplyService gsAppIpApplyService;
    @Autowired
    private UserQueryApi userQueryApi;


    ///////////////////////////////////// IP修改申请单 /////////////////////////////////////

    /**
     * 根据根据订单ID获取订单相信信息
     *
     * @param request
     * @param id
     * @return
     */
    @GetMapping("/getIpApplyInfo")
    public Response getIpApplyInfo(HttpServletRequest request, Integer id) throws BizException {
        UserInfo userInfo = ssoService.getUserInfo(request);
        Assert.isNull(userInfo, "未登录");
        IpApplyInfoVo userApplyInfo = gsAppIpApplyService.getUserApplyInfo(userInfo.getUserId(), id);
        return Response.success(userApplyInfo);
    }

    /**
     * 查询IP修改申请单列表
     *
     * @param request
     * @param page
     * @param appName 自建系统名称 模糊查询
     * @param ip      IP 模糊查询
     * @param state   订单状态
     * @return
     */
    @GetMapping("/getUserIpApplyPageList")
    public Response getUserIpApplyPageList(HttpServletRequest request, Page page, String appName, String ip, Integer state) throws BizException, UnsupportedEncodingException {
        UserInfo userInfo = ssoService.getUserInfo(request);
        Assert.isNull(userInfo, "未登录");
        appName = URLDecoder.decode(appName, "UTF-8");
        IPage<IpApplyListVo> userApplyList = gsAppIpApplyService.getUserApplyList(userInfo.getUserId(), page.getSize(), page.getCurrent(), appName, ip, state);
        return Response.success(userApplyList);
    }

    ///////////////////////////////////// 自建系统 /////////////////////////////////////

    /**
     * 查询用户自建系统列表
     */
    @GetMapping("/listApp")
    public Response listData(HttpServletRequest request) {
        Integer userId = ssoService.getUserInfo(request).getUserId();
        return Response.success(gsAppService.listApp(userId));
    }

    /**
     * 获取该用户某个IP下所拥有的所有资源列表
     *
     * @param request
     * @return
     */
    @GetMapping("/ipListUserRes")
    public Response listUserRes(HttpServletRequest request, Page page, Integer ipId) throws BizException {
        UserInfo userInfo = ssoService.getUserInfo(request);
        Assert.isNull(userInfo, "用户未登录");
        List<IpResListVo> listVos = gsAppService.listUserRes(userInfo.getUserId(), page, ipId);
        PageUtils<IpResListVo> ipResListVoPageUtils = new PageUtils<>(page.getSize(), page.getCurrent(), listVos);
        return Response.success(ipResListVoPageUtils);
    }


    /**
     * 用户取消所申请的需求单
     *
     * @param map     orderItemNo
     * @param request
     * @return
     */
    @PostMapping("/revoke")
    public Response revoke(@RequestBody Map<String, Object> map, HttpServletRequest request) throws BizException {
        UserInfo userInfo = ssoService.getUserInfo(request);
        Assert.isNull(userInfo, "用户未登录");
        Integer itemId = (Integer) map.get("itemId");
        String orderNo = (String) map.get("orderNo");
        GsOrderItem one = gsOrderItemService.getOne(Wrappers.<GsOrderItem>lambdaQuery().eq(GsOrderItem::getOrderItemNo, orderNo + "-" + itemId));
        Assert.isTrue(one.getState() == 5 || one.getState() == 6 || one.getState() == 7, "当前订单状态不可撤回");
        boolean update = gsOrderItemService.update(Wrappers.<GsOrderItem>lambdaUpdate().eq(GsOrderItem::getOrderItemNo, orderNo + "-" + itemId).set(GsOrderItem::getState, 5));
        Boolean withdraw = approvalAllApi.withdraw(orderNo + "-" + itemId, userInfo.getUserId(), new Date(), 1);
        Assert.isTrue(!update || !withdraw, "撤回失败，请重试");
        return Response.success("撤回成功");
    }


    /**
     * 根据当前登录用户查询所申请的需求申请单
     *
     * @param request
     * @return
     */
    @GetMapping("/getUserOrderList")
    public Response getUserSendOrderList(Page<GsOrderItem> page, String orderNo, String resName, Integer state, HttpServletRequest request) throws BizException, UnsupportedEncodingException {
        UserInfo userInfo = ssoService.getUserInfo(request);
        Assert.isNull(userInfo, "用户未登录");
        resName = URLDecoder.decode(resName, "UTF-8");
        IPage<ResOrderPgVO> iPage = gsOrderService.pageUserOrder(page, orderNo, resName, state, userInfo.getUserId());
        return Response.success(iPage);
    }

    /**
     * 查询单个自建系统
     */
    @GetMapping("/getApp")
    public Response getApp(HttpServletRequest request, Integer id) throws BizException {
        checkAppAuth(request, id);
        return Response.success(gsAppService.getApp(id));
    }

    /**
     * 新增自建系统
     */
    @PostMapping("/createApp")
    public Response createApp(@RequestBody GsApp gsApp, HttpServletRequest request) throws BizException {
        gsApp.setUserId(ssoService.getUserInfo(request).getUserId());
        gsAppService.createApp(gsApp);
        return Response.success();
    }

    /**
     * 更新自建系统
     */
    @PostMapping("/updateApp")
    public Response updateApp(@RequestBody GsApp gsApp, HttpServletRequest request) throws BizException {
        UserInfo userInfo = ssoService.getUserInfo(request);
        checkAppAuth(request, gsApp.getId());
        gsAppService.updateApp(gsApp, userInfo.getUserId());
        return Response.success();
    }

    /**
     * 删除自建系统
     */
    @PostMapping("/removeApp")
    public Response removeApp(@RequestBody GsApp gsApp, HttpServletRequest request) throws BizException {
        checkAppAuth(request, gsApp.getId());
        gsAppService.removeApp(gsApp.getId());
        return Response.success();
    }

//    /**
//     * 查询某个自建系统下绑定的应用
//     * @param appId appId
//     * @param ip ip
//     */
//    @GetMapping("/queryAppInterface")
//    public Response queryAppInterface(HttpServletRequest request, Integer appId, String ip) {
//
//    }

    /**
     * 查询某个自建系统的某个ip下已绑定的应用
     *
     * @param appId appId
     * @param ip    ip
     */
    @GetMapping("/listAppIpInterfaceBind")
    public Response listAppIpInterfaceBind(HttpServletRequest request, Integer appId, String ip) throws BizException {
        if (appId == null) {
            return Response.success(Collections.emptyList());
        }
        checkAppAuth(request, appId);
        return Response.success(gsAppService.listAppIpInterfaceBind(appId, ip));
    }

//    /**
//     * 给特定ip绑定服务
//     */
//    @PostMapping("/bindIpInterface")
//    public Response bindIpInterface(HttpServletRequest request, @RequestBody AppIpUpdateVO appIpUpdateVO) throws BizException {
//        checkAppAuth(request, appIpUpdateVO.getAppId());
//        gsAppService.bindIpInterface(ssoService.getUserInfo(request).getUserId(), appIpUpdateVO);
//        return Response.success();
//    }

    /**
     * 校验自建系统权限
     */
    private void checkAppAuth(HttpServletRequest request, Integer appId) throws BizException {
        GsApp app = gsAppService.getById(appId);
        Assert.isNull(app, "应用数据不存在");
        Integer userId = ssoService.getUserInfo(request).getUserId();
        UserDTO user = userQueryApi.getUser(userId);
        Assert.isTrue(!app.getDeptId().equals(user.getOwnDeptId()), "没有访问该自建系统的权限");
    }


    ///////////////////////////////////// 需求申请单 /////////////////////////////////////

    /**
     * 用户订单分页数据
     */
    @GetMapping("/pageOrder")
    public Response pageOrder(HttpServletRequest request, Page<GsOrderItem> page, String resName, Integer orderState) throws BizException, UnsupportedEncodingException {
        Integer userId = ssoService.getUserId(request);
        Assert.isNull(userId, "用户未登录");
        String state = request.getParameter("state");
        String key = request.getParameter("orderNo");
        resName = URLDecoder.decode(resName, "UTF-8");
        IPage<ResOrderPgVO> result = gsOrderService.pageOrder(
                page,
                key,
                resName,
                StringUtil.isBlank(state) ? null : Integer.valueOf(state),
                userId,
                ssoService.getUserId(request),
                orderState
        );
        return Response.success(result);
    }
}
